// pages/register/register.ts
const api = require("../../utils/api");
const util = require("../../utils/common");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    formData: {
      username: '',
      password: '',
      email: ''
    },
    isShow: false
  },
  // 注册
  submitForm() {
    const {username, email, password} = this.data.formData;
    const emailReg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    if (!username) {
      util.showToast('请输入用户名');
    } else if (!email) {
      util.showToast('请输入电子邮箱');
    } else if (!password) {
      util.showToast('请输入密码');
    } else if (!emailReg.test(email)) {
      util.showToast('请输入正确的电子邮箱');
    } else {
      const data = {
        ...this.data.formData,
        roles: 'author',
      }
      api.getAdminToken().then(res => {
        if (res?.token) {
          wx.setStorageSync('token', res.token);
          api.register(data).then(res => {
            if (res?.id) {
              wx.removeStorageSync('token');
              wx.showToast({
                title: '注册成功',
                icon: 'success',
                duration: 1000,
                success: function () {
                  setTimeout(function() {
                    wx.navigateTo({
                      url: `/pages/login/login`,
                    })
                  }, 1000);
                }
              })
            }
          })
        }
      })
    }
  },
  // 输入框
  onChange (e) {
    const field = e.target.dataset.field;    
    this.setData({
      [`formData.${field}`]: e.detail.value
    }) 
  },
  onIconChange () {  
    this.setData({
      isShow: !this.data.isShow
    })
  }
})